# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '18112600001910': {  # dwc 付宝2.5%（100-5000）D0结算
        'API_KEY': 'A4AB4E9B407FB34D93456D4A1DF0BAB0',
        'gateway': 'http://120.77.216.125:8889/tran/cashier/pay.ac',
        'query_gateway': 'http://120.77.216.125:8889/tran/cashier/query.ac',
        'org_no': '0181100292',  # 商户机构号
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_org_no(mch_id):
    return APP_CONF[mch_id]['org_no']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    _LOGGER.info("newpay sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("newpay notify sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return '0506'
    return '0506'


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']
    parameter_dict = OrderedDict((
        ('version', '2.1'),
        ('orgNo', _get_org_no(app_id)),
        ('custId', str(app_id)),
        ('custOrderNo', str(pay.id)),
        ('tranType', _get_pay_type(service)),
        ('payAmt', int(pay_amount * 100)),
        ('backUrl', '{}/pay/api/{}/newpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('goodsName', 'charge'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    url = _get_gateway(app_id)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    _LOGGER.info("newpay create: url: %s, %s", url, json.dumps(parameter_dict))
    response = requests.post(url, data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("newpay create: response: %s", response.text)
    data = json.loads(response.text)
    cache_id = redis_cache.save_html(pay.id, data['busContent'])
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("newpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['custOrderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('newpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = str(data['ordStatus'])
    trade_no = data['prdOrdNo']
    total_fee = float(data['ordAmt']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    # 支付状态：00:未交易 01:成 功 02:失败 06:未支付.
    if trade_status == '01' and total_fee > 0.0:
        _LOGGER.info('newpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('version', '2.1'),
        ('orgNo', _get_org_no(app_id)),
        ('custId', app_id),
        ('custOrderNo', str(pay_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    _LOGGER.info("newpay create: url: %s, %s", _get_query_gateway(app_id), json.dumps(parameter_dict))
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("newpay create: response: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)

        verify_notify_sign(data, api_key)

        mch_id = pay_order.mch_id
        trade_status = str(data['ordStatus'])
        total_fee = float(data['payAmt']) / 100.0
        trade_no = str(data['prdOrdNo'])
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 00:未交易 01:成 功 02:失败 06:未支付.
        if trade_status == '01' and total_fee > 0.0:
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('newpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
